<template>
    <el-dialog title="编辑" :model-value="visible" width="520px" :fullscreen="mobile" @close="handleImageClose">
        <el-form label-width="0">
        <div class="fs-base fc-secondary mb10">
            凭证图片 (限3张，图片大小不超过10M)
        </div>
        <el-form-item prop="fileList">
            <el-upload
                v-model:file-list="fileList"
                :action="uploadUrl"
                :headers="headers"
                list-type="picture-card"
                :on-remove="handleImageRemove"
                :before-upload="handleImageBeforeUpload"
                :on-exceed="handleImageOnExceed"
                :on-success="handleImageOnSuccess"
                :multiple="true"
                :auto-upload="false"
                :limit="3"
                accept="image/png, image/jpeg"
                :class="{'is-full': fileList.length === 3}"
                ref="picRef"
            >
            <el-icon><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="handleImageClose">取消</el-button>
            <el-button type="primary" @click="handleImageOk">
            保存
            </el-button>
        </span>
        </template>
    </el-dialog>
</template>
<script setup>
import useAppStore from '@/store/modules/app'
import { getCurrentInstance, watchEffect } from 'vue';
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
    visible: {
        type: Boolean, 
        default: false
    },
    images: {
        type: Array,
        default: () => {
            return []
        }
    }
})
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传的图片服务器地址
const headers = ref({ authorization: getToken() })
const fileList = ref([])
const mobile = computed(() => useAppStore().device === 'mobile')
watchEffect(() => {
    fileList.value = [...props.images]
})

// 编辑图片弹窗
function handleImageClose() {
  emit('cancel')
}
function handleImageOk() {
  proxy.$refs['picRef'].submit()
}

// 图片上传
function handleImageRemove(uploadFile, uploadFiles) {
  console.log(uploadFile, uploadFiles)
}
function handleImageBeforeUpload(file) {
  console.log(file);
  
  if (file.type.indexOf("image/") == -1) {
    proxy.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
    return false
  }
  const isLtSize = file.size / 1024 / 1024 < 2
  if (!isLtSize) {
    proxy.$modal.msgError("请上传小于2MB的图片。")
    return false
  }
  return true
}
// 当超出限制时，执行的钩子函数
function handleImageOnExceed(files) {
  proxy.$modal.msgWarning("最多只能选择三张图片")
}
function handleImageOnSuccess(res, file, files) {
  let count = 0
  let picUrl = []
  files.forEach(item => {
    if (item.response && item.response.code !== 200) {
      proxy.$modal.msgError(item.name + '上传失败：' + item.response.msg)
    } else {
      count++
      picUrl.push({
        name: item.response ? item.response.data.name : item.name,
        url: item.response ? item.response.data.url : item.url,
      })
    }
  })
  if (count === fileList.value.length) {
    emit('ok', JSON.stringify(picUrl))
  }
}
</script>